/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui;

import core.Database;
import core.DatabaseTable;
import core.TableColumn;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.apache.log4j.Logger;
import ui.helpers.EditColumnListener;

/**
 *
 * @author Sakis Vtdk <sakis.vtdk@gmail.com>
 */
public class ColumnActionsPanel extends javax.swing.JPanel {

	/**
	 * Creates new form ColumnActionsPanel
	 */
	public ColumnActionsPanel() {
		initComponents();
	}

	public ColumnActionsPanel(TableColumn column, int parentId)
	{
		initComponents();

		this._column = column;
		this._parentTableId = parentId;

		//set name
		nameTextField.setText(column.getName());

		//set data types
		dataTypeComboBox.removeAllItems();
		for(TableColumn.DataType dataType : TableColumn.DataType.values())
		{
			dataTypeComboBox.addItem(dataType.toString());

			//check if the item has to be selected
			if(dataType.toString().equals(column.getDataType(false)))
			{
				dataTypeComboBox.setSelectedItem(dataType.toString());
			}
		}

		//set size
		if(toggleSizeFieldEnabled())
		{
			int size = column.getSize();
			sizeTextField.setText(Integer.toString(size));
		}
		else
		{
			sizeTextField.setText("N/A");
		}

		//set default value
		defaultValueTextField.setText(column.getDefaultValue());

		//set auto increment
		autoIncrementCheckBox.setSelected(column.isAutoIncrement());

		//set is primary key
		primaryKeyCheckBox.setSelected(column.isPrimaryKey());

		// add an event listener to enable/disable the sizeField
		dataTypeComboBox.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				toggleSizeFieldEnabled();
				toggleAutoIncrementEnabled();
			}
		});
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        nameLabel = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        dataTypeLabel = new javax.swing.JLabel();
        dataTypeComboBox = new javax.swing.JComboBox();
        sizeLabel = new javax.swing.JLabel();
        sizeTextField = new javax.swing.JTextField();
        defaultValueLabel = new javax.swing.JLabel();
        defaultValueTextField = new javax.swing.JTextField();
        autoIncrementCheckBox = new javax.swing.JCheckBox();
        primaryKeyCheckBox = new javax.swing.JCheckBox();
        submitButton = new javax.swing.JButton();
        submitButton.addActionListener(new EditColumnListener());
        errorLabel = new javax.swing.JLabel();

        setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        nameLabel.setText("Name");
        add(nameLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, -1, -1));

        nameTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                nameTextFieldFocusLost(evt);
            }
        });
        add(nameTextField, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 30, 60, -1));

        dataTypeLabel.setText("Data Type");
        add(dataTypeLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, -1));

        dataTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        add(dataTypeComboBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 60, -1, -1));

        sizeLabel.setText("Size");
        add(sizeLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, -1, -1));
        add(sizeTextField, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 90, 60, -1));

        defaultValueLabel.setText("Default Value");
        add(defaultValueLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1));
        add(defaultValueTextField, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 120, 60, -1));

        autoIncrementCheckBox.setText("AutoIncrement");
        add(autoIncrementCheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 160, -1, -1));

        primaryKeyCheckBox.setText("Primary Key");
        add(primaryKeyCheckBox, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 180, -1, -1));

        submitButton.setText("Submit");
        add(submitButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 220, -1, -1));
        add(errorLabel, new org.netbeans.lib.awtextra.AbsoluteConstraints(99, 282, 149, -1));
    }// </editor-fold>//GEN-END:initComponents

    private void nameTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_nameTextFieldFocusLost
		//first check if there is a change
		if(!this.nameTextField.getText().equals(this._column.getName()))
		{
			Database db = Database.getDatabase();
			DatabaseTable tbl = db.getTable(this._parentTableId);	

			if(tbl.columnExists(nameTextField.getText()))
			{
				String errorString = "Column with this name already exists!\n";

				errorLabel.setText(errorString);

				//TODO: change the color of the error message and change the color of the name label
			}
			else
			{
				errorLabel.setText("");
			}
		}

    }//GEN-LAST:event_nameTextFieldFocusLost

	/**
	 * Enables or disables the sizeTextField  based on the selected DataType
	 * @return True if the sizeTextField is enabled, false if not
	 */
	private boolean toggleSizeFieldEnabled()
	{
		String selectedDataType = dataTypeComboBox.getSelectedItem().toString();
		boolean dataTypeHasSize = TableColumn.DataType.valueOf(selectedDataType).hasSize();
			
		if(dataTypeHasSize)
		{
			Integer size = this._column.getSize();
			if(size == null || size == 0)
			{
				sizeTextField.setText(((Integer) this._column.getDefaultSize()).toString());
			}
			else
			{
				sizeTextField.setText(size.toString());
			}
		}
		else
		{
			sizeTextField.setText("N/A");
		}

		sizeTextField.setEnabled(dataTypeHasSize);

		return dataTypeHasSize;
	}

	/**
	 * Toggles whether the autoIncrementCheckbox should be enabled or not
	 * 
	 * @return Whether or not the autoIncrementCheckBox is enabled
	 */
	private boolean toggleAutoIncrementEnabled()
	{
		String selectedDataType = dataTypeComboBox.getSelectedItem().toString();
		boolean isAutoIncrementable = TableColumn.DataType.valueOf(selectedDataType).isAutoIncrementable();

		autoIncrementCheckBox.setEnabled(isAutoIncrementable);

		return isAutoIncrementable;
	}

	public void setIsPopup(boolean isPopup)
	{
		_isPopup = isPopup;
	}

	public boolean getIsPopup()
	{
		return _isPopup;
	}

	public int getParentTableId()
	{
		return this._parentTableId;
	}

	public String getSizeTextFieldText()
	{
		return this.sizeTextField.getText();
	}

	public Boolean isAutoIncrement()
	{
		return this.autoIncrementCheckBox.isSelected();
	}

	public Boolean isPrimaryKey()
	{
		return this.primaryKeyCheckBox.isSelected();
	}

	public String getDefaultValueTextFieldText()
	{
		return this.defaultValueTextField.getText();
	}

	public TableColumn getTableColumn()
	{
		return this._column;
	}

	public String getNameTextFieldText()
	{
		return this.nameTextField.getText();
	}

	public String getSelectedType()
	{
		return this.dataTypeComboBox.getSelectedItem().toString();
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox autoIncrementCheckBox;
    private javax.swing.JComboBox dataTypeComboBox;
    private javax.swing.JLabel dataTypeLabel;
    private javax.swing.JLabel defaultValueLabel;
    private javax.swing.JTextField defaultValueTextField;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JCheckBox primaryKeyCheckBox;
    private javax.swing.JLabel sizeLabel;
    private javax.swing.JTextField sizeTextField;
    private javax.swing.JButton submitButton;
    // End of variables declaration//GEN-END:variables

	private TableColumn _column;
	private int _parentTableId;
	private boolean _isPopup = false;

	private static Logger log = Logger.getLogger(ColumnActionsPanel.class);
}
